package com.dh.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class MyReentrantLock {
	
	private  Lock lock = new ReentrantLock();
	//通过创建Condition对象来使线程wait，必须先执行lock.lock方法获得锁
	private  Condition condition=lock.newCondition();
	
	public  void testMethod() {
		//效果和synchronized一样，都可以同步执行，lock方法获得锁，unlock方法释放锁
        try {
			for (int i = 0; i < 5; i++) {
				lock.lock();
	            System.out.println("a");
	            //System.out.println("开始wait");
	            condition.signal();
	            //通过创建Condition对象来使线程wait，必须先执行lock.lock方法获得锁
	            condition.await();
		    }
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
    }
	
	public  void signal(){
		//condition对象的signal方法可以唤醒wait线程
        try{
        	//System.out.println("开始唤醒锁");
            for (int i = 0; i < 5; i++) {
            	lock.lock();
            	System.out.println();
	            System.out.println("b");
	            condition.signal();
	            condition.await(1000, TimeUnit.SECONDS);
		    }
        } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
            lock.unlock();
        }
    }
	
	public static void main(String args[]) {
		MyReentrantLock lo=new MyReentrantLock();
		new Thread(new Runnable() {
			@Override
			public void run() {
				lo.testMethod();
			}
		}).start();
		new Thread(new Runnable() {
			@Override
			public void run() {
				lo.signal();
			}
		}).start();
	}

}
